package jaux.tank.generator;


import java.awt.EventQueue;
import java.awt.event.WindowEvent;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.prefs.Preferences;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import jaux.tank.generator.component.TankGeneratorFrame;
import jaux.tank.generator.util.MessageUtil;
import jaux.tank.generator.util.TextUtil;
import lombok.Getter;

public class MainApp {
    private TankGeneratorFrame frame;
   

    public static void main(String[] args) {
    	
        EventQueue.invokeLater(() -> {
            try {
                MainApp app = new MainApp();
                app.frame.setVisible(true);
                app.frame.focusTree();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public MainApp() {
        initialize();
    }

    private void initialize() {
        // 设置国际化资源
        Locale locale = Locale.getDefault(); // 从系统默认设置获取当前语言设置
        // get stored language
        Preferences prefs = Preferences.userNodeForPackage(MainApp.class);
		String storedLocale = prefs.get("locale", null);
		if (storedLocale != null) {
			locale = Locale.forLanguageTag(storedLocale);
		}
        TextUtil.getInstance().setLocale(locale);
        // get stored style
		String storedStyle = prefs.get("style", null);
		if (storedStyle != null) {
			try {
				UIManager.setLookAndFeel(storedStyle);
			} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
					| UnsupportedLookAndFeelException e) {
				e.printStackTrace();
			}
		}
        frame = new TankGeneratorFrame(this);
       
    }

    public void restart() {
		EventQueue.invokeLater(() -> {
			if(!frame.checkTankSaved()) {
				return;
			}
			try {

				frame.setVisible(false);
				frame.dispose();
				initialize();
				frame = new TankGeneratorFrame(this);
				frame.setVisible(true);
				frame.focusTree();
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
    }
    public void changeStyle(String className) {
		String currentLafClassName = UIManager.getLookAndFeel().getClass().getName();
		if(currentLafClassName.equals(className)) {
			return;
		}
		// ask restart
		boolean confirmRestart = MessageUtil.isYes(this.frame, TextUtil.getInstance().getString("message.confirm.root.restart"));
		if(confirmRestart) {
			// store new style
			Preferences.userNodeForPackage(MainApp.class).put("style", className);
			restart();
		}
		
	}

	public void changeLanguage(Locale locale) {
		// ask restart
		boolean confirmRestart = MessageUtil.isYes(this.frame, TextUtil.getInstance().getString("message.confirm.root.restart"));
		if(confirmRestart) {
			// store new language
			Preferences.userNodeForPackage(MainApp.class).put("locale", locale.toLanguageTag());
			restart();
		}

	}
}